;(function(){
 	// 当前站点名称
	var siteName = $page.site;  
	// member子域名  需要配host才能造数据  cart子域是我们的系统host都已配置好
    // home    主站
    // secondHand  残次品站点
    // warranty    延保站点
    // contractPhone   合约机站点
    // groupOn 团购站点
    // rushBuy 抢购站点
    // haiwaigou   海外购站点
    // presell 预售站点  
    // directionalCoupon   定向券站点

    // 子域名，用于拼接空购物车跳转
    var subDomain        = {};
    subDomain.home       = 'www';
    subDomain.groupOn    = 'tuan';
    subDomain.rushBuy    = 'q';
    subDomain.secondHand = 'tao';
    subDomain.warranty   = 'www';
    subDomain.presell    = 'www';

    // 添加商品时候的类型字段，用于购物车添加商品的部分
    var addGoodType = {};
    addGoodType.home = 0;
    addGoodType.hwg = 16;  // 海外购 
    addGoodType.ext = 5;   // 延保商品
    addGoodType.jjg = 6;   // 加价购

    // 当前购物车logo返回首页的链接地址
    var siteDomain = 'http://' + (subDomain[siteName] || 'www') + cookieDomain;

	// var cookieDomain = '.atguat.com.cn';

	// 判断是否是ie6浏览器
	var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6')>-1;

	// 修复ie6下javascript协议的a标签会造成图片加载停止和ajax取消
	if(isIE6){
		$(document).on('click', 'a', function(e){
			var href = this.href + '';
			if(href.indexOf('javascript:') == 0){
				e.preventDefault();
			}
		});
	};

	// 下拉框展示的时候提高下拉框所在元素的z-index，防止被遮挡
	$(document).on('popshow selectshow', '.cart-shop-header,.cart-shop-good,.cart-shop-info', function () {
		$(this).addClass('high-level');
	}).on('pophide selecthide', '.cart-shop-header,.cart-shop-good,.cart-shop-info', function () {
		$(this).removeClass('high-level');
	}); 

	// 所有的ajax接口在这里配置
	var api = {
		// 拉取登录信息
		loginInfo: 'http://g.atgsit.com.cn/ec/homeus/navigation/gome/index/loginStyle.jsp'
		// 拉取购物车
		,loadCart: '/api/cart/loadCart'
		// 选中、取消单个商品
		,selectItem: '/api/cart/selectItem'
		,cancelItem: '/api/cart/cancelItem'
		// 选中、取消店铺
		,selectItemsByShopNo: '/api/cart/selectItemsByShopNo'
		,cancelItemsByShopNo: '/api/cart/cancelItemsByShopNo'
		// 全选、反选
		,selectAllItem: '/api/cart/selectAllItem'
		,cancelAllItem: '/api/cart/cancelAllItem'
		// 修改商品数量
		,changeCount: '/api/cart/changeNum'
		// 删除商品
		,removeItem: '/api/cart/removeItem'
		// 批量删除
		,batchRemoveItem: '/api/cart/batchRemoveItem'
		// 生成订单，去下一页
		,checkout: '/api/checkout/checkout'
        // 海外购生成订单
        ,checkoutHWG: '/api/checkout/checkoutHWG' 
		// 加入购物车
		// http://cart.atguat.com.cn/home/api/cart/addToCart?type=0&sid=sku21000024&pid=prod21070048&pcount=1
		,addToCart: '/api/cart/addToCart'

		// 拉取优惠券信息 
        // http://cart.atguat.com.cn/home/api/couponQuery/loadAllFetchCoupon
		,loadAllFetchCoupon: '/api/couponQuery/loadAllFetchCoupon'


		// 领取商铺券
		// http://cart.atguat.com.cn/home/api/coupon/fetchCoupon
		,fetchCoupon: '/api/coupon/fetchCoupon'

		// 到货通知
		,goodsNoticeVerify: 'http://g' + cookieDomain + '/ec/homeus/browse/goodsNoticeVerify.jsp'
		// http://g.atguat.com.cn/ec/homeus/browse/goodsNoticeVerify.jsp?
		// callback=notice&productId=prod18190070&skuId=sku18120020&oldPrice=2000.10&mail=2432%40fa.cc&tell=18510871788&city=11011400 

		// 自营商品选择促销信息
		// http://cart.atguat.com.cn/home/api/promotion/claimGomePromotion?cid=2000005016&prid=P170139
		,claimGomePromotion: '/api/promotion/claimGomePromotion'

        // 联营商品选择促销信息
        // http://cart.atguat.com.cn/home/api/promotion/claimShopPromotion?shopno=80000517&prid=3622
        ,claimShopPromotion: '/api/promotion/claimShopPromotion'

		// 修改配送区域
		// /api/transport/changeTransportDistrict?p=11000000&c1=11010000&c2=11010200&t=110102001
		,changeTransportDistrict: 'http://cart' + cookieDomain + '/api/district/changeTransportDistrict' 

	};

	// 给api的url增加host;
	// var apiHost = '/' + siteName;
	var apiHost = '/' + siteName;
	for(var url in api){
		if(api[url].indexOf('http://') != 0){
			api[url] = apiHost + api[url];
		} 
	} 

	// 延保购物车单独接口
	if(siteName == 'warranty'){
		api.loadCart = 'http://success' + cookieDomain + '/api/loadCart/loadWarrantyCart';
	}

	// 事件代理，所有的页面功能事件都写在这里
	// 注：这里是bindActEvents方法使用的，限于功能实现。UI事件在bindUiEvents里
	var events = { 
        // 选中、取消单个商品
        'gcheckbox.change [act-check-item]': function(){  
            var $this = $(this);
            var checked = $this.find('[type=checkbox]').prop('checked');

            cartApp.call({
                url: checked? api.selectItem : api.cancelItem
                ,data: {
                    cid: $this.data('cid')
                }
                ,success: function(cartData){
                    if( cartData.errCode != "0"){
                        panel.error(cartData.errMsg);
                        cartApp.renderCacheCart();
                    }else{
                        cartApp.loadCart();
                    } 
                }
                ,error: function () {
                    cartApp.renderCacheCart();
                }
            }); 
        } 
		// 选中、取消商铺商品
		,'gcheckbox.change [act-check-shop-item]': function(){
			var $this = $(this);
			var checked = $this.find('[type=checkbox]').prop('checked');
			cartApp.call({
				url: checked? api.selectItemsByShopNo : api.cancelItemsByShopNo
				,data: {
					sno: $this.data('sid')
				}
				,success: function(cartData){
					if( cartData.errCode != "0"){
                        panel.error(cartData.errMsg);
                        cartApp.renderCacheCart();
                    }else{
                        cartApp.loadCart();
                    } 
				}
                ,error: function () {
                    cartApp.renderCacheCart();
                }
			}); 
		} 
		// 全选、取消全选
		,'gcheckbox.change [act-check-all-items]': function(){
			var $this = $(this);
			var checked = $this.find('[type=checkbox]').prop('checked');
			cartApp.call({
				url: checked? api.selectAllItem : api.cancelAllItem
				,success: function(cartData){
					if( cartData.errCode != "0"){
                        panel.error(cartData.errMsg);
                        cartApp.renderCacheCart();
                    }else{
                        cartApp.loadCart();
                    } 
				}
				,error: function () {
                    cartApp.renderCacheCart();
                }
			}); 
		} 
		// 修改商品数量
		,'count-change [act-change-count]': function(event, value, oldValue){
			var $this = $(this); 
            if(value === ''){
                cartApp.renderCacheCart();
            }else if(value <= 0){ 
                // 购物车商品数量少于0    
                panel.error('商品数量必须大于0');
                cartApp.renderCacheCart();
			}else{  
                var limit = $this.data('limit');
                if(value > limit){
  					$config.cartAtom.limitTip=$this.data('cid');
                    cartApp.renderCacheCart();
                    $config.cartAtom.limitTip=null;
                    return;
                }
                cartApp.call({
                    url: api.changeCount
                    ,data: {
                        cid: $this.data('cid')
                        ,pcount: value
                    }
                    ,success: function(cartData){
                        if(cartApp.isFail(cartData)){
                            panel.error(cartData.errMsg);
                            cartApp.renderCacheCart();
                        }else{
                            cartApp.loadCart();
                        }
                    }
                });
            } 
		}
        // 点击需要弹出内容的
        ,'click [act-alert]': function () {
            panel.error(this.getAttribute('act-alert'));
        }
		// 批量删除
		,'click [act-batch-remove-item]': function(){ 
            var $this = $(this);
			var cids = [];
			var datas = [];
			$('[name=good]:checked').each(function(){
				var $this = $(this);
				cids.push(this.value); 

				// data-title="${good.itemName}"
				// data-url="${good.href}"
				// data-sid="${good.skuId}"
				// data-pid="${good.productId}"
				var data = {};
				data.title = $this.data('title');
				data.url   = $this.data('url');
				data.sid   = $this.data('sid');
				data.pid   = $this.data('pid'); 
				data.cid   = $this.data('cid'); 
				data.price = (Number($this.data('price')) || 0).toFixed(2); 
				data.count = $this.data('count'); 
                data.hwg = $this.data('hwg');
                data.save = $this.data('save');

				datas.push(data);
			}); 
			if(!cids.length){
				return panel.error('没有选中任何商品');
			}
			panel.confirmOk({
				title:"删除商品!",
				body:"确认要删除选中商品吗？"
			},function(dialog){
				dialog.hide();
				request.reqp(api.batchRemoveItem,{
					cids:cids.join(",")
				}).then(function(data){
					if(cartApp.isFail(data)){
						panel.error(data.errMsg);
						return;
					}
					cartApp.loadCart(); 
                    cartApp.addDeletedItem(datas); 
				});
			});
 
		}
		// 删除商品   
		,'click [act-remove-item]': function(){
			var $this = $(this); 

			// data-title="${good.itemName}"
			// data-url="${good.href}"
			// data-sid="${good.skuId}"
			// data-pid="${good.productId}"
			var data = {};
			data.title = $this.data('title');
			data.url   = $this.data('url');
			data.sid   = $this.data('sid');
			data.pid   = $this.data('pid'); 
			data.cid   = $this.data('cid'); 
			data.price = (Number($this.data('price')) || 0).toFixed(2); 
			data.count = $this.data('count');  
            data.hwg = $this.data('hwg');
            data.save = $this.data('save');
			function removeItem(dialog){
				cartApp.call({
					url: api.removeItem
					,data: {
						cid: $this.data('cid')
					}
					,success: function(cartData){
						cartApp.loadCart(); 
                        cartApp.addDeletedItem(data); 
					}
				});
				dialog.hide();
			}
			function fn2(confirm){
				$this.parent().parent().find("[act-add-wishlist]").trigger("click");
				confirm.hide();
			}
			if(cartApp.isHome()){
				panel.confirm({
					type:panel.TYPE.WARN,
					title:"删除商品?",
					body:"您可以选择移入收藏夹，或删除商品",
					close:util_ui.hide,
					btns:[
						{
							btnName:"删除",
							clazz:"btn btn-default",
							click:removeItem
						},{
							btnName:"移入收藏夹",
							clazz:"btn btn-primary",
							click:fn2
						}
					]
				});
			}else{
				panel.confirmOk({title:"删除商品?",body:"确定要删除商品吗"},removeItem);
			}
		} 
		// 添加延保
		// http://cart.atguat.com.cn/home/api/cart/addToCart?type=0&mid=111&wsid=sku21420017&wpid=prod21500036
		,'change [act-change-warranty]': function () {  
			var $this = $(this);
			var vals = ($(this).val()).split('|');
			if(vals[0] == 'add'){
				cartApp.call({
					url: api.addToCart
					,data: {
						mid: vals[1]
						,wsid: vals[2]
						,wpid: vals[3]
						,type: addGoodType.ext// 区分站点的，修改延保写死是5

					}
					,success: function(cartData){
						cartApp.loadCart();
					}
                    ,error: function () {
                        cartApp.renderCacheCart();
                    }
				});
			}else if(vals[0] == 'del'){ 
				cartApp.call({
					url: api.removeItem
					,data: {
						cid: vals[1]
					}
					,success: function(cartData){
						cartApp.loadCart(); 
					}
                    ,error: function () {
                        cartApp.renderCacheCart();
                    }
				});
			}
			 
		}
		// 延保购物车添加延保
		,'click [act-add-warranty]': function () {
			var $this = $(this); 
			var vals = ($(this).data('infos')).split('|'); 
			if( !$this.hasClass('cart-ext-item-selected') ){
				cartApp.call({
					url: api.addToCart
					,data: {
						mid: vals[0]
						,wsid: vals[1]
						,wpid: vals[2]
						,type: addGoodType.ext               // 区分站点的，修改延保写死是5
						,mpid: vals[4]
					}
					,success: function(cartData){
						cartApp.loadCart();
					}
                    ,error: function () {
                        cartApp.renderCacheCart();
                    }
				});
			}else{ 
				cartApp.call({
					url: api.removeItem
					,data: {
						cid: vals[3]
					}
					,success: function(cartData){
						cartApp.loadCart(); 
					}
                    ,error: function () {
                        cartApp.renderCacheCart();
                    }
				});
			}
		}
		//弹窗登陆
		,'click [act-user-login]':function(){
			 //login 弹框
			 cartApp.glogin();	
		}
		// 初始化订单确认页面
		,'click [act-init-order]': function(){
			var $this = $(this);  
			if($this.hasClass('init-disabled') || $this.hasClass('btn-status-loading')){
				return;
			}

            var data;
            if($this.data('hwg')){
                data = {
                    isHwg: true
                };
            }

            $this.addClass('btn-status-loading');

            initOrder();

            function initOrder(){
                cartApp.call({
                    url: ((data && data.isHwg) ? api.checkoutHWG : api.checkout)
                    ,data: data
                    ,success: function(cartData){
                        $this.removeClass('btn-status-loading');
                        if(cartData.errCode == '0'){
                            if(data && data.isHwg){
                                location.href = '/haiwaigou' + $config.URL.shopping;
                            } else {
                                if(siteName == 'home'){
                                    location.href = $config.URL.shopping;
                                }else if(siteName == 'warranty'){
                                    // location.href = '/warranty/shopping'; //+ siteName + $config.URL.shopping;
                                    location.href = '/warranty/shopping?' + cartApp.warrantyOrderId;
                                }else{
                                    location.href = '/' + siteName + $config.URL.shopping;
                                }
                                
                            } 
                        } else { 
                            if(cartData.errCode == "003000001"){
                            	//login 弹框
                           		cartApp.glogin(initOrder);	
                            }else{
                            	var obj={
                            		type:panel.TYPE.ERROR,
                            		content:cartData.errMsg || '结算失败，请重试'
                            	};
                                panel.alertClose(obj,function(dialog){
                                	util_ui.hide(dialog);
	                                /*
	                                0010360030=您添加商品的数量超过限购数量.
	                                0010360050=预约活动还未开始.
	                                0010360051=您没有参加预约活动.
	                                0010360052=您已参加预约活动,不能重复购买.
	                                */

	                                if(
	                                    cartData.errCode == '0010360030' || 
	                                    cartData.errCode == '0010360050' || 
	                                    cartData.errCode == '0010360051' || 
	                                    cartData.errCode == '0010360052'){
	                                    cartApp.loadCart();
	                                }
                                });
                            } 
                        }
                        
                    }
                    ,error: function () {
                    	panel.error('生成订单超时，请重试。');
                        $this.removeClass('btn-status-loading');
                    }
                });
            }; 
		} 
        // 促销优惠的弹层关闭之后恢复购物车原状态 
        ,'pophide [act-good-prom]': function () { 
            var $this = $(this);
            $this.find('input:checked').prop('checked', false);
            $this.find('[data-default]').prop('checked', true); 
        }
		// 加入收藏夹
		,'click [act-add-wishlist]': function(){
			// http://ss.gome.com.cn/item/v1/sc/9133251702/1122160101/72002982196/homeSite/flag/sc/wishlist?callback=wishlist&_=1452168210611
			var $this = $(this); 
			//弹窗提示
			function okfn(dialog){
				addToWishlist($this); 
				dialog.hide();
			}
            if(cartApp.isLogin()){
                panel.confirmOk({title:"移入收藏夹!",body:"移动后选中商品将只在收藏夹内显示"},okfn);
            }else{ 
               cartApp.glogin();
            }

            // 加入收藏夹 copy
            function addToWishlist($dom){
            	//var uid = $('[act-login-name]').attr('uid');
            	var uid = cartApp.getUserId();

            	//var uid = cartApp.uid; 
                var url = 'http://ss' + cookieDomain + '/item/v1/sc/' + $dom.data('pid') + '/' + $dom.data('sid') + 
                        '/' + uid + '/' + siteName + '/flag/cart/wishlist'; 

                cartApp.call({
                    url: url
                    ,jsonpName: 'wishlist'
                    ,success: function(cartData){  
                        if(cartData.success == 'true' ){ 
                            cartApp.call({ 
                                url: api.removeItem
                                ,data: {
                                    cid: $dom.data('cid')
                                }
                                ,success: function(cartData){  
                                    cartApp.loadCart();
                                    cartApp.loadFavorites();

                                    // 如果是在删除区加入收藏夹，则去掉删除区项目
                                    var $wrap = $this.parents('[act-deleted-wrap]');
                                    if($wrap.length){
                                        var $list = $this.parents('[act-deleted-list]');
                                        $this.parents('[act-deleted-item]').remove();
                                        if(!$list.find('[act-deleted-item]').length){
                                            $wrap.hide();
                                        }
                                    } // end if
                                }
                            });  
                        }else{ 
                        	panel.alert(cartData.errorType == "isCollect" ? '您已收藏过此商品' : ( cartData.message || '收藏失败！'));
                            //cartApp.alert(cartData.errorType == "isCollect" ? '您已收藏过此商品' : ( cartData.message || '收藏失败！'));
                            cartApp.loadFavorites();
                        } 
                    }
                }); 
            } // end addToWishlist 

		}
		// 收藏夹添加购物车
		,'click [act-add-cart]': function(type){ 
			// 加入购物车
			// http://cart.atguat.com.cn/home/api/cart/addToCart?type=0&sid=sku21000024&pid=prod21070048&pcount=1 
			// type=0&sid=sku21000024&pid=prod21070048&pcount=1
			var args=arguments;
			var $this = $(this);
			$this.addClass("cart-scroll-click-background");
            if($this.hasClass('cart-scroll-btn-disabled')){
                return;
            }
			cartApp.call({
				url: api.addToCart
				,data: {
					sid: $this.data('sid')
					,pid: $this.data('pid')
					,pcount: 1
					,type: type||$this.data('hwg') ? addGoodType['hwg'] : addGoodType[siteName]             // 区分站点的 todo
				}
				,success: function(cartData){
					if(cartData.errCode == '0'){
						// cartApp.alert('加入购物车成功');
						var $tip = $this.siblings('.cart-scroll-image').find('.cart-scroll-tip');
						$tip.show();
						setTimeout(function () {
							$tip.hide();
						}, 2000);
						cartApp.loadCart();
						// if($this.data('gid')){
						// 	cancelFavoritesGoods({
						// 		gid: $this.data('gid')
						// 		,sid: $this.data('sid')
						// 		,pid: $this.data('pid')
						// 	});
						// } 
					}else if(cartData.errCode == '001004002'){
                        // data-limit-${good.skuId}-${good.productId} 
                        var $limit = $('[data-limit-' + $this.data('sid').toLowerCase() + '-' + $this.data('pid').toLowerCase() + ']'); 
                        var limit = $limit.data('limit-' + $this.data('sid').toLowerCase() + '-' + $this.data('pid').toLowerCase());
                        if(limit){ 
                            panel.alert('您购物车中的相同商品购买数量不能大于' + limit + '件');
                        }
                    }else if(cartData.status == "MTK_V"){//虚拟卡
	                    window.location.href='http://card'+cookieDomain+"?productId="+$this.data('pid')+"&skuId="+$this.data('sid')+"&count="+1+"&skuType=ZDZK";           
	                    return;
	                }else if(cartData.status == "MTK_E"){//实体卡
	                	window.location.href='http://card'+cookieDomain+"?productId="+$this.data('pid')+"&skuId="+$this.data('sid')+"&count="+1+"&skuType=ZSTK";           
	                	return;
	                }else{ 
                    	if(type==null) return args.callee(16);
						panel.error(cartData.errMsg || '加入购物车失败');
					} 
				}
                ,error: function (e) {
                    panel.error('加入购物车失败，请重试');
                }
			});  
			// http://member.gome.com.cn/myaccount/myFavorites/cancelFavoritesGoods?
			// callback=ckdata&
			// removeGomeGiftitemIds=696873&
			// removeGomeProductIds=A0004925323&
			// removeGomeSkuIds=pop8004390585  
			// function cancelFavoritesGoods(data){
			// 	cartApp.silentCall({
			// 		url: 'http://member' + cookieDomain + '/myaccount/myFavorites/cancelFavoritesGoods'
			// 		,jsonpName: 'ckdata'
			// 		,data: {
			// 			removeGomeGiftitemIds: data.gid
			// 			,removeGomeProductIds: data.pid
			// 			,removeGomeSkuIds: data.sid
			// 		}
			// 		,success: function(cartData){
			// 			cartApp.loadFavorites();
			// 		}
			// 	});  
			// } // end cancelFavoritesGoods 
		}
		// 删除区 - 重新添加购物车
		,'click [act-rebuy]': function(){
			// http://cart.atguat.com.cn/home/api/cart/addToCart?type=0&sid=sku21000024&pid=prod21070048&pcount=1 
			// type=0&sid=sku21000024&pid=prod21070048&pcount=1
			var $this = $(this);
			cartApp.call({
				url: api.addToCart
				,data: {
					sid: $this.data('sid')
					,pid: $this.data('pid')
					,pcount: $this.data('count')
					,type: $this.data('hwg') ? addGoodType['hwg'] : addGoodType[siteName]             // 区分站点的 todo
				}
				,success: function(cartData){ 
					if(cartData.errCode == '0'){
						// cartApp.alert('加入购物车成功');
						cartApp.loadCart();

						var $wrap = $this.parents('[act-deleted-wrap]');
						var $list = $this.parents('[act-deleted-list]');
						$this.parents('[act-deleted-item]').remove();
						if(!$list.find('[act-deleted-item]').length){
							$wrap.hide();
						}
					}else if(cartData.errCode == '001004002'){
                        // data-limit-${good.skuId}-${good.productId} 
                        var $limit = $('[data-limit-' + $this.data('sid').toLowerCase() + '-' + $this.data('pid').toLowerCase() + ']'); 
                        var limit = $limit.data('limit-' + $this.data('sid').toLowerCase() + '-' + $this.data('pid').toLowerCase());
                        if(limit){ 
                            panel.alert('您购物车中的相同商品购买数量不能大于' + limit + '件');
                        }
                    }else{ 
						panel.error(cartData.errMsg || '加入购物车失败');
					} 
				}
                ,error: function (e) {
                    panel.error('加入购物车失败，请重试');
                }
			}); 
		}
        // 获取店铺券
		,'refresh [act-get-coupon]': function(){ 
			var $this = $(this);
			cartApp.silentCall({
				url: api.loadAllFetchCoupon
				,data: {
					shopno: $this.data('sid') 
				}
				,success: function(cartData){ 
					if(cartData.errCode == '0'){ 
						var tpl = cartApp._couponTpl;
						if(!tpl){
							tpl = cartApp._couponTpl = $('#couponTpl').html();
						}

						if(!cartData.data || !cartData.data[0] || !cartData.data[0].shopCoupons){
							return;
						}

						var html = '';
						var coupons = cartData.data[0].shopCoupons;
						for(var i=0,data; data=coupons[i++]; ){ 
							var startDate = new Date(+data.startDate);
							var expirationDate = new Date(+data.expirationDate);

							data.startDate = [
								startDate.getFullYear() 
								,(startDate.getMonth()+1) 
								,startDate.getDate()
							].join('.');

							data.expirationDate = [
								expirationDate.getFullYear() 
								,(expirationDate.getMonth()+1) 
								,expirationDate.getDate()
							].join('.'); 
							
							html += tpl.replace(/\$\{([^\}]+)\}/g, function(a, b){ 
								return data[b] || '';
							});
						} 
						$this.siblings('.cart-coupon-box').find('.cart-coupon-items').html(html);
					}else{ 
						// cartApp.alert(cartData.errMsg || '拉取优惠券失败');
					} 
				}
			}); 
		}
		// 领取商铺劵
		,'click [act-add-coupon]': function () {
			var $this = $(this);
            if($this.hasClass('cart-coupon-btn-disabled')){
                return;
            }

            function getCoupon() {
                cartApp.silentCall({
                    url: api.fetchCoupon
                    ,data: {
                        couponid: $this.data('cpid') 
                        ,activeid: $this.data('aid') 
                    }
                    ,success: function(cartData){ 
                        if(cartData.errCode == '0'){ 
                            // cartApp.alert('领取成功！'); 

                            var offset = $this.offset();
                            var $addone = $('<div class="cart-coupon-addone">+1</div>'); 
                            $addone.appendTo(document.body).css({
                                left: (offset.left - 130)
                                ,top: offset.top
                            }).animate({
                                top: (offset.top - 100)
                                ,opacity: 0
                            }, function () {
                                $(this).remove();
                            });

                          if($this.data('quantity') == 1){

                           //if(1==1){ debugger
                                $this.addClass('cart-coupon-btn-disabled');
                                //领完处理UI
                                $this.prev().prev()
                                .css("borderColor","#ccc")
                                .find(".cart-coupon-icon-inner")
                                .css("background","#ccc");
                               // $this.prev().prev().find(".cart-coupon-icon-inner").css("background","#ccc");
                                $this.prev()
                                .children("div")
                                .css("color","#ccc");

                                $this.html('已领完');  
                            }else{
                            	$this.html('继续领取');  
                            }
                        }else if(cartData.errCode == '003000001'){ 
                        	cartApp.glogin(getCoupon);
                            
                        }else{
                            panel.error(cartData.errMsg);
                            $this.addClass('cart-coupon-btn-disabled');
                            $this.html('已领完');  
                             //领完处理UI
                             $this.prev().prev()
                             .css("borderColor","#ccc")
                             .find(".cart-coupon-icon-inner")
                             .css("background","#ccc");
                             $this.prev()
                             .children("div")
                             .css("color","#ccc"); 

                            // $this.parents('.cart-coupon')
                            //     .find('[act-get-coupon]')
                            //     .trigger('refresh');
                        } 
                    }
                }); 
            };

            getCoupon();
			
		}
        // 加价购确定
        ,'click [act-add-jjg]': function () { 
            // http://cart.atguat.com.cn/home/api/cart/addToCart?type=6&sps=sku20880028_prod21060028&spid=P200345
            var $this = $(this);
            var $cbs = $this.parents('.cart-add-buy-list-inner').find(':checked');
            var sps = '';
            $cbs.each(function (i) {
                if(i){
                    sps += ',';
                }
                sps += this.value;
            });

            cartApp.call({
                url: api.addToCart
                ,data: {
                    type: addGoodType.jjg
                    ,sps: sps
                    ,spid: $this.data('id')
                }
                ,success: function(cartData){
                    if(cartData.errCode == '0'){
                        cartApp.loadCart();
                    }else{
                        panel.error(cartData.errMsg);
                        cartApp.renderCacheCart();
                    }
                }
                ,error: function () {
                    cartApp.renderCacheCart();
                    panel.error('加价换购失败，请重试');
                }
            }); 
        } 
		// 到货通知 
		,'click [act-arrival-notice]': function(){
			// callback=notice
			// productId=prod18190070
			// skuId=sku18120020
			// oldPrice=2000.10
			// mail=2432%40fa.cc
			// tell=18510871788
			// city=11011400 
			var $this = $(this);
			var tpl = this._dialogTpl;
			if(!tpl){
				tpl = this._dialogTpl = $('#arrival-notice').html();
			}

			var html = tpl.replace(/\$\{([^\}]+)\}/g, function(a, b){ 
				return data[b] || '';
			});

			var dialog = $.gDialog({
				html: html
				,modal:{
				}
			});
			dialog.show(); 
            // 独立站点的到货通知没有加入收藏夹
            if(!$this.data('fav')){ 
                dialog.$dialog.find('.add').hide();
            } 

			dialog.$dialog.on('click', '[act-submit]', function(){  
				var $phoneno = dialog.$dialog.find('[name=phoneno]');
				var $email = dialog.$dialog.find('[name=email]');
                var $checked = dialog.$dialog.find(':checked');
				var data = {};
				data.productId = $this.data('pid');
				data.skuId = $this.data('sid');
				data.oldPrice = $this.data('price');
				data.tell = $.trim($phoneno.val());
				data.mail = $.trim($email.val());
				data.city = getArea3();   

				if(data.tell == ''){  
					return $phoneno.siblings('span').show().html('<i></i>手机号不能为空');
				}else if(!/^1[3578]\d{9}/.test(data.tell)){
					return $phoneno.siblings('span').show().html('<i></i>手机号格式不正确');
				}else{
					$phoneno.siblings('span').hide();
				}
				if(data.mail && !/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(data.mail)){
					return $email.siblings('span').show().html('<i></i>邮箱格式不正确');
				}else{
					$email.siblings('span').hide();
				} 

				cartApp.call({
					url: api.goodsNoticeVerify
					,jsonpName: 'notice'
					,data: data
					,success: function (data) {
						panel.success(data.msg);
						dialog.hide(); 
                        if($checked.length){
                            addToWishlist($this); 
                        }else{} 
					}
					,error: function () {
						dialog.hide(); 
						panel.error('请求接口失败');
					}
				}); 
			});
			dialog.$dialog.on('click', '[act-close]', function(){  
				dialog.hide(); 
			}); 


            // 加入收藏夹
            function addToWishlist($dom){ 
                 //var uid = $('[act-login-name]').attr('uid');
                 var uid = cartApp.getUserId();
                //var uid = cartApp.uid; 
                var url = 'http://ss' + cookieDomain + '/item/v1/sc/' + $dom.data('pid') + '/' + $dom.data('sid') + 
                        '/' + uid + '/' + siteName + '/flag/cart/wishlist';                         
                cartApp.call({
                    url: url
                    ,jsonpName: 'wishlist'
                    ,success: function(cartData){  
                        if(cartData.success == 'true'){ 
                            cartApp.call({
                                url: api.removeItem
                                ,data: {
                                    cid: $dom.data('cid')
                                }
                                ,success: function(cartData){  
                                    cartApp.loadCart();
                                    cartApp.loadFavorites();
                                }
                            });  
                        }else{ 
                            panel.alert(cartData.errorType == "isCollect"? '您已收藏过此商品' : ( cartData.message || '收藏失败！'));
                            cartApp.loadFavorites();
                        } 
                    }
                }); 
            } // end addToWishlist 
		} 
		// 切换自营商品的促销类型 
		,'click [act-claimGomePromotion]': function () {  
			var $this = $(this);
			var pid = $this.parents('.cart-coupon-items').find(':checked').val();
			if(pid == 'no_use'){
				pid = '';
			}
			cartApp.silentCall({
				url: api.claimGomePromotion
				,data: {
					cid: $this.data('cpid') 
					,prid: pid
				}
				,success: function(cartData){ 
					if(cartData.errCode == '0'){ 
						cartApp.loadCart();
					}else{ 
						cartApp.renderCacheCart();
						panel.alert('切换促销失败！'); 
					} 
				}
                ,error: function () {
                    cartApp.renderCacheCart();
                }
			});
		}
        // 切换联营促销信息
        // http://cart.atguat.com.cn/home/api/promotion/claimShopPromotion?shopno=80000517&prid=3622
        ,'change [act-change-promotion]': function () {   
            var $this = $(this);
            var vals = ($(this).val()).split('|'); 
            cartApp.call({
                url: api.claimShopPromotion
                ,data: {
                    shopno: vals[0]
                    ,prid: vals[1]
                }
                ,success: function(cartData){
                    if(cartData.errCode == '0'){
                        cartApp.loadCart();  
                    }else{
                        cartApp.renderCacheCart();
                        panel.error('切换促销失败！'); 
                    } 
                }
                ,error: function () {
                    cartApp.renderCacheCart();
                }
            });   
        }
        // todo
        ,'gcheckbox.change [act-jjg-check]': function () { 
            var $this = $(this);
            var $parent = $this.parents('.cart-add-buy-row');
            var max = $parent.data('max');
            var checked = $parent.find(':checked').length; 
            if(checked > max){
                $this.find('input')[0].checked = false;
                $.gCheckbox.render($this);

                $this.siblings('.cart-add-buy-tip').show();
                
                clearTimeout($this.data('_timer'));
                $this.data('_timer', setTimeout(function(){
                    $this.siblings('.cart-add-buy-tip').hide();
                }, 2000)); 
                

            } else {
                cartApp.renderJJGCount();
            }
        }
	};
	//商品属性列表处理逻辑
	function salesPropertyfn(list){
		var r = list;
		var r = util.take(2,r);
		return r;
	}


	//预售阶段逻辑
	function presellItemfn(list,goodpresell){	
		var r=util.tail(list);
		//checked //i 是当前选中的
		//{{if !presellStep._isArriveActive}}已{{/if}}满${presellStep.needCount}人
		//被选中的预售阶段 [选中-> 那个被选中 -> 处理]
		var checkedPrellIdx=0,currentCount=goodpresell.currentApplyCount;
		for(var i=0;i<r.length;i++){
			if(r[i].checked)checkedPrellIdx=i;
		}
		function getPreNeedCount(arr,ci){
			if(ci==0)return 0;
			return arr[ci-1].needCount; 
		}
		var pNeedCount=getPreNeedCount(r,checkedPrellIdx);
		for(var i=0;i<r.length;i++){
			var item=r[i];
			if(i<checkedPrellIdx){
				item.showMsg="满"+item.needCount+"人";
				item.backgroundcolor="#fff4f4";
				item.linebackgroundcolor="#ffcccb";
				item.fontcolor="#5e5e5e";
			}
			if(i==checkedPrellIdx){
				var a=item.needCount-pNeedCount;
				var b=currentCount-pNeedCount;
				item.jindu=Math.min(b/a*100,100);
				item.showMsg="满"+item.needCount+"人";
				item.backgroundcolor="#fff";
				item.linebackgroundcolor="#f00";
				if(item.jindu>0 && item.jindu==100){
					item.fontcolor="#333";
					item.fontsize = "16px";
					item.fontweight = "bold";
				}
			}
			if(i>checkedPrellIdx){
				item.showMsg="满"+item.needCount+"人";
				item.backgroundcolor="#f8f8f8";
				item.linebackgroundcolor="#ccc";
				item.fontcolor="#5e5e5e";
			}
			/*if(currentCount < item.needCount){
				item.showMsg="满"+item.needCount+"人";
				item.backgroundcolor="#f8f8f8";
				item.linebackgroundcolor="#ccc";
				item.fontcolor="#5e5e5e";	
				item.fontweight = "400";
				item.fontsize = "12px";
			}*/
		}
		return r;
	}

	function setPreCartData(data){
		data.prevHeight=cartApp._prevHeight;
		return data;
	}
	function renderTpl(tplfn){
		return function(data){
			// try{
	            $('.cart-lists').html(tplfn(data));
	        // }catch(e){
	        //     panel.error('系统错误请稍后重试');
	        // }
	        return data;
		}
	}
	function afterRender(cartData){
		if(isCartEmpty(cartData)){
			$('.cart-area').hide();  
			$('.cart-lists').html(GTPL.cart_empty(cartData));
		}else{
			$('.cart-area').show();  
		}
        var cityOption = {
            gc_ads:'chtm',
            gc_evt:function(){
                //重写城市cookie
                $.cookie('atgregion', this.xid+"|"+this.chtm+"|"+this.cid+"|"+this.sid+"|"+this.zid, {expires:30,path:'/',domain:cookieDomain});
                //重写八叉乐cookie
                $.cookie('atgMboxCity', this.snam, {expires:30,path:'/',domain:cookieDomain});

                // /api/transport/changeTransportDistrict?p=11000000&c1=11010000&c2=11010200&t=110102001
                cartApp.silentCall({
                    url: api.changeTransportDistrict
                    ,data: {
                        p: this.sid // 省
                        ,c1: this.cid // 城
                        ,c2: this.xid // 县
                        ,t: this.zid // 镇
                    }
                    ,success: function (data) {
                        if(data && data.success){
                            cartApp.loadCart();
                        }else{
                            panel.error('修改区域失败，请重试.');
                        }
                    }
                    ,error: function () {
                        panel.error('修改区域失败，请重试.');
                    }
                }); 
            }
        };
        if(isCartEmpty(cartData)==false){
			$('#address').gCity(cityOption);
		}
         

		// 渲染各个UI组件
		$.gCheckbox.render();
		$.gCount.render();
		$.gSelect.render();

		// 绑定底部fixed条事件
		cartApp.bindFixedBottom();
		if(cartApp._prevHeight){ 
			cartApp._prevHeight = $('[act-list]>div').height();
			$('[act-list]').animate({height: cartApp._prevHeight});
		}else{ 
			cartApp._prevHeight = $('[act-list]>div').height(); 
		}


        cartApp.renderJJGCount();
        cartApp.renderKfStatus();

        util_watch.emit($page.name,"renderEnd",cartData);
	}
	//是否延保站点
	function isWarrantySite(){
		return $page.site=="warranty";
	}
	//判断是否是二手站点
	function isSecondHandSite(){
		return $page.site=="secondHand";
	}
    //判断是否团购
    function isgroupOn(){
    	return $page.site == "groupOn";
    }
    //判断是否抢购
    function isrushBuy(){
    	return $page.site == "rushBuy";
    }
    //判断是否预售
    function isPresellSite(){
    	return $page.site == "presell";
    }
	//判断是否是主站
	function isHome(){
		return $page.site=="home";
	}
	//延保购物车是否为空
	function isWarrantyCartEmpty(cartData){
		return !(cartData && cartData.data && cartData.data.commerceItemVOs && cartData.data.commerceItemVOs.length);
	}
	//判断购物车是否为空
	function isPrimaryCartEmpty(cartData){
		return !(cartData && cartData.data && cartData.data.siVOs && cartData.data.siVOs.length);
	}
	var isCartEmpty=util.cond([
		[isWarrantySite,isWarrantyCartEmpty],
		[util.T,isPrimaryCartEmpty]
	]);
	var u=util;
	//如果条件返回true 返回自身，否则执行后置条件
	var  logicLess=u.ifn(u.__,u.identity,u.__);
	//渲染购物车
	//如果是空购物车跳过渲染 否则渲染 并执行渲染后的逻辑
	var renderCart=u.cond([
		[isWarrantySite,u.pipe(setPreCartData,logicLess(isCartEmpty,renderTpl(GTPL.cart_warranty)),afterRender)]
		,[isPresellSite,u.pipe(setPreCartData,logicLess(isCartEmpty,renderTpl(GTPL.cart_presell)),afterRender)]
		,[util.T,u.pipe(setPreCartData,logicLess(isCartEmpty,renderTpl(GTPL.cart_new)),afterRender)]
	]);
	//判断用户是否登录
	var user=(function(){
		var uid=$.cookie("SSO_USER_ID");
		var logined=uid!=null&&uid!="";
		function loadUser(){
			request.getJson("/api/loginStyle").then(function(data){
				if(isFail(data))return;
				uid=data.data.loginId;
				//假登录
				if(data.data.loginStatus=="fakeLogin"){
					logined=false;
					return;
				}
				//已登录
				if(data.data.loginStatus=="logined"){
					logined=true;
					return;
				}
				logined=false;
				util_watch.emit($page.name,"login",data);
			});
		}
		function isLogin(){
			return logined;
		}
		function getUserId(){
			return uid;
		}
		loadUser();
		return {
			isLogin:isLogin,
			loadUser:loadUser,
			getUserId:getUserId
		}
	}());

	//用户登录弹窗 公共登录有坑，请使用这个
	function glogin(fn){
		g.login(function () { 
		    $.cookie("g_checkCart","true",{expires:1, path:'/', domain:cookieDomain}); 
			signData.gloginfn=null;
	    	cartApp.reload();
		    util_watch.watchOnce($page.name,"renderEnd",function(){
		    	if(fn)fn();
		    });
		    user.loadUser();
		}); 
	}
	//判断数据响应是否失败
	function isFail(data){
		if(data==null)return true;
		if(data.errCode=="0") return false;
		return true;
	}

	//商品状态
	function itemState(good){
		if(!isSecondHandSite()&&good.inventoryState == "OFF") return '<div class="red">已下架</div>';
		if(good.inventoryState=="NO_GOODS")return '<div class="red">无货</div>';
		if(good.inventoryState=="INVENTORY_TENSION")return '<div class="red">库存紧张</div>';
		if(good.inventoryState=="DELIVERY_NOT_SUPPORTED")return '<div class="red">该区域暂不支持配送</div>';
		return "";
	}
	//获取三级区域 默认三级区域11011400
	function getArea3(){
		var area3=($.cookie("atgregion") || '') .split("|")[0];
		if(area3==null||area3=="")return "11011400";
		return area3;
	}
	// 购物车整体代码 
	var cartApp = {
		glogin:glogin
		,isFail:isFail
		,isrushBuy:isrushBuy
		,isgroupOn:isgroupOn
		,isWarrantySite:isWarrantySite
		,isLogin:user.isLogin
		,getUserId:user.getUserId
		,presellItemfn:presellItemfn
		,salesPropertyfn:salesPropertyfn
		,isHome:isHome
		,itemState:itemState
		,isCartEmpty:isCartEmpty
		,getArea3:getArea3
		,init: function(){ 
			// this.loadCart(true);
            this.loadCart();
            if(isHome()){
                // 只有主站有底部栏
                this.initBottom();
            }
			this.bindActEvents();   
			this.bindUiEvents(); 
		}
		,initCartData:function(data){
			cartApp.doCartAction(data);
			if(isHome()){
                // 只有主站有底部栏
                this.initBottom();
            }
			this.bindActEvents();   
			this.bindUiEvents(); 
		}
		// 重新刷新购物车所有区块
		,reload: function () {
			cartApp.loadCart();
			cartApp.loadFavorites();
			cartApp.loadHistory();
			cartApp.loadRecommend();
			signData.init();//顶通用户登录

		}
		// 调用api，调用时显示loading
		,call: function(options){
			if(!options){
				throw new Error('no options.');
			} 

			var success = options.success;
			var error = options.error;
			// 超过300毫秒没成功的接口显示loading
			var timerId = setTimeout(function(){
				cartApp.showLoading();
			}, 500);

			options.success = function(data){
				clearTimeout(timerId);
				timerId = null;
				cartApp.hideLoading();

				if(data && data.errCode == '0010010110'){ 
					return cartApp.loadCart();
				}
				if(success){
					success.apply(this, arguments); 
				}   
			}

			options.error = function(){ 
				clearTimeout(timerId);
				timerId = null;
				cartApp.hideLoading();


				if(error){
					error.apply(this, arguments); 
				}   
			}
			/*options.timeout = 10000;*/
			options.dataType = 'jsonp'; 
			$.ajax(options);
		}
		// 调用api
		,silentCall: function(options){
			if(!options){
				throw new Error('no options.');
			} 
			var success = options.success; 
			options.success = function(data){
				if(data && data.errCode == '0010010110'){
					return cartApp.loadCart();
				}
				if(success){
					success.apply(this, arguments); 
				}  
			} 
			/*options.timeout = 10000;*/
			options.dataType = 'jsonp'; 
			$.ajax(options);
		}
		,doCartAction:function(cartData){
			var defaultData = {
            	siteName: siteName
            	,siteDomain: siteDomain
            };

            cartData.siteName = siteName;  
            // 只有主站有选择框
            if(isHome()){
                cartData.hasCheckbox = true;
                cartData.hasAddFavorites  = true; 
                cartData.hasDeleteArea = true; 
            }else{
                cartData.hasCheckbox = false;
                cartData.hasAddFavorites  = false;
                cartData.hasDeleteArea = false;
            }
            // 二手站点没有商品数量增减框
            if(siteName == 'secondHand'){
                cartData.hasChangeCount =  false;
            }else{
                cartData.hasChangeCount =  true;
            }

            // 空购物车去购物链接跳转地址
            cartData.siteDomain = siteDomain;

			if(cartApp.isFail(cartData)){ 
				//团抢处理
					if(cartData.status == "GO_LOGIN"){
						cartApp.glogin();
						return;	
					} 
				panel.error('很抱歉，系统繁忙，请稍后在试 <br>你可以返回 <a class="alertatag" href="http://www'+cookieDomain+'"> 国美在线首页</a> 继续购物');	
				if(cartApp._cacheData){
					cartApp.renderCart(cartApp._cacheData);   
				} else {
                    cartApp.renderCart(defaultData);
                }

			} else{
				cartApp._cacheData = cartData; 
				cartApp.renderCart(cartData); 
			} 
		} 
		// 加载购物车数据
		,loadCart: function(isSilent){    
			
			var data = {};
			// 延保购物车需要传orderId
			if(isWarrantySite()){
				var str=window.location.href.split("?")[1];
				if(str!=null)str=str.split("&")[0];
				cartApp.warrantyOrderId = data.orderId =str;
			}
			cartApp[isSilent ? 'silentCall' : 'call']({ 
				url: api.loadCart 
				,data: data
				,success: cartApp.doCartAction
				,error: function(){
					panel.error('很抱歉，系统繁忙，请稍后在试 <br>你可以返回 <a class="alertatag" href="http://www'+cookieDomain+'"> 国美在线首页</a> 继续购物');	
					if(cartApp._cacheData){
                        cartApp.renderCart(cartApp._cacheData);   
                    } else {
                        cartApp.renderCart(defaultData);
                    }
				}
			});   
		}

        // 用上次缓存的数据渲染购物车
        ,renderCacheCart: function () {
            if(cartApp._cacheData){
                cartApp.renderCart(cartApp._cacheData);
            }else{
                cartApp.loadCart();
            }
        }

		// 加载底部我的收藏、最近浏览模块 
		// 为您推荐模块
		,initBottom: function(){ 
			// 底部的tab切换
			cartApp.initTab(); 
		}
		// 我的收藏、最近浏览、为您推荐模块的滚动
		,initScroller: function($scrollContainer){  
			var $prevBtn = $scrollContainer.find('.scroll-left-btn');
			var $nextBtn = $scrollContainer.find('.scroll-right-btn');


			var $scrollView = $scrollContainer.find('.scroll-view'); 
			var $items = $scrollView.find('.cart-scroll-item');
 
			if($items.length <= 5){ 
				$prevBtn.hide();
				$nextBtn.hide();
				return;
			}

			$prevBtn.show();
			$nextBtn.show();

			if(!$items.length){
				return;
			};
			$items.remove();
			var $viewScroller = $('<div style="position: absolute; left:0; top:0; width: 9999px;"></div>');
			$scrollView.append($viewScroller)

			var currIndex = 0;
			var count = 5;
			function getGroup(type){ 
				var moveDistance = $scrollView.width();
				var $removeDoms = $scrollView.find('.cart-scroll-item');

				if(type == 'prev'){
					var tmpIndex = currIndex - 1;
					for(var i=0; i<count*2; i++){ 
						if(!$items.eq(tmpIndex).length){ 
							tmpIndex = $items.length-1;
						} 
						if(i<count){
							tmpIndex--; 
							currIndex = tmpIndex + 1;
							continue;
						}else{
							$viewScroller.prepend($items.eq(tmpIndex).clone(false));
						}; 
						tmpIndex--;
					}

					$viewScroller.stop(true, true).css({
						left: -moveDistance
					}).animate({left: 0}, 300, function(){ 
						$removeDoms.remove();
					});
				}else if(type == 'next' || type == 'init'){
					for(var i=0; i<count; i++){ 
						if(!$items.eq(currIndex).length){ 
							currIndex = 0;
						}

						$viewScroller.append($items.eq(currIndex).clone(false)); 
						currIndex++;
					}

					if(type == 'next'){
						$viewScroller.stop(true, true).animate({
							left: -moveDistance
						}, 300, function(){
							$(this).css({left: 0})
							$removeDoms.remove();
						});
					}else{
						$viewScroller.css({left: 0})
						$removeDoms.remove();
					}
					
				} 
			};

			getGroup('init');
			$prevBtn.off().on('click', function(){
				getGroup('prev');
			});
			$nextBtn.off().on('click', function(){
				getGroup('next');
			});  
		}
		// 渲染我的收藏、最近浏览、为您推荐模块
		,renderBottomItems: function(data, $dom,type){
			var html = '';
			$(data).each(function(){   
				html += cartApp.renderBottomItem(this);
			});
		    if($dom){
				if(html==null||html==""){
					html=GTPL['bottom_empty_'+type](cartApp);
				}
				$dom.find('.scroll-view').html(html);
				cartApp.initScroller($dom);
			}
			return html;
		} 
		,renderBottomItem: function(data){
            return GTPL.bottom_item(data);
		}
		// 加载我的收藏
		,loadFavorites: function(){   
			if(!cartApp.isLogin()){
				cartApp.renderBottomItems(null, $('[data-favorites]'),'favorites'); 
				return;
			}
            // currPageNum=1& pageSize=15& districtCode=110102005
			// var requestUrl = 'http://member'+cookieDomain+'/myaccount/myFavorites/getMyFavoritesGoods';
            var requestUrl = 'http://member'+cookieDomain+'/myaccount/myFavorites/getFavoritesGoodsForShopCart';

			cartApp.silentCall({
				url: requestUrl 
				,jsonpName: 'ckdata'
                ,data: {
                   // userId: cartApp.uid
                   userId:cartApp.getUserId()
                    ,currPageNum: 1
                    ,pageSize: 15
                    ,districtCode: getArea3()
                }
				,success: function(data){  
					var result = [];

					var list;
					try{
						list = data.result.favoritesList.pagination.list;
					}catch(e){

					}
					if(list){ 
						$(list).each(function(){ 
							var fixData        = {};
							fixData.url        = this.productUrl;
							fixData.image      = this.imageUrl;
							fixData.title      = this.displayName;
							fixData.price      = this.skuPrice;
							fixData.sid        = this.skuId;
							fixData.pid        = this.productId;
							fixData.type       = this.shopFlag,
							fixData.giftId     = this.giftItemId; 
                            fixData.isOnlyShow = this.isOnlyShow;
                            if(this.shopFlag == 2 || this.shopFlag == 3){
								fixData.isHWG = true;
							}

							result.push(fixData);
						});  
					}
					var html = cartApp.renderBottomItems(result, $('[data-favorites]'),'favorites');  
				}
				,error: function(){
					var html = cartApp.renderBottomItems(null, $('[data-favorites]'),'favorites'); 
				}
			})
		}
		// 加载最近浏览 
		,loadHistory: function(){  
			//接口参考 profilehomelive.js 
			var pids = $.cookie("proid120517atg");  
			try{
				pids = JSON.parse(pids);
			}catch(e){ 
				pids = ''; 
			} 
	        if(!pids){
	        	var html = cartApp.renderBottomItems(null, $('[data-history]'),'history');  
	        	return;
	        }; 
	        var url = 
	    		'http://ss' +
	    		cookieDomain + 
	    		'/item/v1/browse/prdreturn/' + 
	    		pids.join(',') +
			    '/100/flag/item/wp'; 
			request.reqp(url,{
				currPageNum: 1
                ,pageSize: 15
                ,districtCode: getArea3()
			},"wp").then(function(data){
				var result = [];
		        if (data.success) { 
		            $.each(data.result, function(i, item) { 
		            	if(!item.skuId)return;

            			var fixData    = {};
						fixData.url    = this.url;
						fixData.image  = this.pic;
						fixData.title  = this.name;
						fixData.price  = $.trim(this.price || '');
						fixData.sid    = this.skuId;
						fixData.pid    = this.productId;
						fixData.type   = this.shopFlag; 
						if(this.shopFlag == 2 || this.shopFlag == 3){
							fixData.isHWG = true;
						}
	                	result.push(fixData);  
					});   
		        }
		        var html = cartApp.renderBottomItems(result, $('[data-history]'),'history'); 
			}).fail(function(){
				var html = cartApp.renderBottomItems(null, $('[data-history]'),'history');  
			});
		}

		// 加载为您推荐
		,loadRecommend: function(isEmpty){
			// var quantity = cart.result.cart ? cart.result.cart.cartSummary.totalQuantity : 0;
			// sBoxId = quantity ? 'box16' : 'box15'; 
			var $goodItems = $('[data-good]');
			/*setTimeout(function(){
			var sss = $('.cart-shop-good').data('sid');
				console.log(sss);
			},3000)*/
			var sid = [];
			var pid = [];
			$goodItems.each(function(){
				var $this = $(this);
				sid.push($this.data('sid'));
				pid.push($this.data('pid'));
				// debugger
			});
	
			var param = {}
			//param.cid = $.cookie("__c_visitor");
			param.cid = $.cookie("__clickidc");
			param.uid = cartApp.getUserId();
			param.area      = cartApp.getArea3();
			param.sid       = sid.join(',');
			param.pid       = pid.join(',');

			param.boxid     = (isEmpty ? 'box15' : 'box16'); 
			param.imagesize = 100; 
			var url = 'http://bigd.gome.com.cn/gome/rec';
			cartApp.silentCall({
				url: url
				,data: param
				,success: function(data){
					var result = []; 
					if(data.size==0){
						var html = cartApp.renderBottomItems(null, $('[data-recommend]'),'recommend');
					}else{
						if(data.lst && data.lst.length){
							$(data.lst).each(function(){ 
								var fixData         = {};
								fixData.url         = this.purl;
								fixData.image       = this.iurl;
								fixData.title       = this.pn;
								fixData.price       = $.trim(this.price || ''); 
								fixData.sid         = this.sid;
								fixData.pid         = this.pid;
								fixData.gprice      = $.trim(this.gprice || '');
								fixData.maima_param = this.maima_param; 
								if(this.shopFlag == 2 || this.shopFlag == 3){
									fixData.isHWG = true;
								}

								result.push(fixData);
							}); 
						} 
						var html = cartApp.renderBottomItems(result, $('[data-recommend]'),'recommend');
					}
				}
				,error: function(){
					var html = cartApp.renderBottomItems(null, $('[data-recommend]'),'recommend');
				}
			}); 
		}

		// 绑定所有刷新购物车事件，events在此文件最上面配置的
		,bindActEvents: function(){ 
			var $doc = $(document); 
			for(var type in events){
				var event = type.split(/\s+/); 
				$doc.on(event[0], event[1], events[type]);
			} 
		} 

		// 绑定UI交互事件
		,bindUiEvents:function () {   
			$(document).on('gcheckbox.change', '.cart-shop-good', function (e, checked) { 
				var $this = $(this);
				if(checked){
					$this.addClass('cart-shop-good-checked');
				}else{
					$this.removeClass('cart-shop-good-checked');
				}
			}); 
			$.gCheckbox.bind(); 
			$.gPopup.bind(); 
            $.gPopup.bind('mouseover'); 
			$.gSelect.bind();
		}
		,renderKfStatus: function () { 

			//find在线客服
			var ServerID_arr = [];
			$('[data-customer_service_id]').each(function () {
				ServerID_arr.push($(this).data('customer_service_id'));
			});

			if (ServerID_arr.length > 0) {
				//调用live800接口
				$.ajax({
					type:'get',
					url:'http://ss'+cookieDomain+'/item/v1/online/'+ServerID_arr.join(',')+'/'+cartApp.getUserId()+'/flag/item/live800',
					dataType:'jsonp',
					jsonpName:"live800",
					success: function(data){ 
						//改变客服状态
						$('[data-customer_service_id]').each(function () {
							var customers = data.customers || [];
							for (var i = 0 ; i < customers.length; i++) {
								if (customers[i].customer_flag == $(this).data('customer_service_id')) {
									$(this).data('customer_service', customers[i]);
									if (customers[i].statu == 0) {
										$(this).find('i').removeClass("c-kf-on").addClass('c-kf-off');
									} else if (customers[i].statu == 1) {
										$(this).find('i').removeClass("c-kf-off").addClass('c-kf-on');
										$(this).find('.contact-customer-word').addClass('contact-font');
									}
									if (typeof $(this).data('customer_service_cb') == 'function') {
										$(this).data('customer_service_cb').call(this);
									};
								}
							}
						}); 

						//弹出客服窗口
						$('[data-customer_service_id]').off('click.kf').on('click.kf', function () {
							var customer_service = $(this).data('customer_service');
							if (customer_service.statu<1) {
								return;
							}
							// if (loginData.loginName == '') {
							if( $('[act-login-name]').html() == '' ){
								location.href = g.url.login + '/login?tableName=login&orginURI=' + location.href;
								return;
							}
							if (customer_service) {
								if (customer_service.statu < 0) {
									return;
								}
								window.open(customer_service.host + //host
									'/chatClient/chatbox.jsp?' +
									'companyID=' + customer_service.customerID +
									'&customerID=' + customer_service.customerID +
									'&info=' + customer_service.customerInfo +
									'&page=0' +
									'&enterurl=' + location.href+
									'&shopname=' + encodeURI(encodeURI( $(this).data("shopname")  ) ),
									'customerService' + $(this).data(customer_service).customerID,// 窗口id
									'toolbar=0,scrollbars=0,location=0,menubar=0,resizable=1,width=1120,height=700'
								);
							};
						});
					}
				});
			}
		}

		// 读取数据之后渲染购物车列表
		,renderCart:renderCart
        // 加价换购已选中的数量渲染
        ,renderJJGCount: function () {
            $('.cart-add-buy-list-inner').each(function () {
                var $this = $(this);
                var $red = $this.find('.cart-add-buy-header .cart-red-text').eq(1);
                var checked = $this.find('.cart-add-buy-row :checked').length;
                $red.html(checked);
            });  
        }

		// 底部固定 IE6无视了
		,bindFixedBottom: function(){ 
			var $cartBottomWrap = $('.cart-bottom-wrap'); 
			var cartBottomWrapHeight=$cartBottomWrap.height();
			var isFixed = false;
			if(!$cartBottomWrap.length){
				return;
			}   

			var setBottomFixed =  function(){
				var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
				var bottomPosition = scrollTop + $(window).height(); 
				if(Math.ceil($cartBottomWrap.offset().top) + cartBottomWrapHeight > bottomPosition){ 
					if(isFixed){
						return;
					}
					isFixed = true;
					$cartBottomWrap.addClass('cart-bottom-fixed');  
				}else{ 
					if(!isFixed){
						return;
					}
					isFixed = false;
					$cartBottomWrap.removeClass('cart-bottom-fixed');  
				}
			}
			setBottomFixed();
			$(window)
				.off('scroll.fixedBottom resize.fixedBottom')
				.on('scroll.fixedBottom resize.fixedBottom', setBottomFixed);
		}
		// 往删除列表里添加已删除商品
		,addDeletedItem: function(datas){
			if(!datas.length){
				datas = [datas];
			}
			var tplfn=GTPL.cart_deleted_item;

            var hasItem = false;
			
			$(datas).each(function (i, data) {
                if(!this.save){
                    return;
                }
                hasItem = true;
				var html = '';
				html =tplfn(data);
				var $dom = $('[act-deleted-wrap] [data-id=' + data.pid + '-' + data.sid + ']');
				if($dom.length){ 
					 $dom.replaceWith(html);
				}else{ 
                    $('[act-deleted-wrap] [act-deleted-list]').append(html);
				} 
			});  

            if(hasItem){
                $('[act-deleted-wrap]').show();  
            } 
		}
		// 拉取完底部我的收藏、为您推荐、最近浏览的数据之后渲染
		,initTab: function(){ 
			var $tab = $('.cart-bottom-tab');
            $tab.show();
			var $tabTrigger = $tab.find('.cart-tab-header a');
			var $tabContent = $tab.find('.cart-tab-content');

            // // 加载我的收藏
            // cartApp.loadFavorites();
            // // 加载最近浏览
            // cartApp.loadHistory(); 

			$tabTrigger.each(function(i){
				$(this).mouseover(function(){
                    if(i == 1){
                    	cartApp.loadHistory();  
                    }else if(i==2){
                        cartApp.loadFavorites();
                    };
					$tabTrigger.removeClass('active').eq(i).addClass('active');
					$tabContent.hide().eq(i).show();
				});
			});
			$tabTrigger.eq(0).mouseover(); 
		}

		// 显示整个页面的loading对话框
		,showLoading: function(){
			/*if(this._loading){
				return;
			}
			var loading = this._loading = $.gDialog({
				html: '<div class="loading-icon"></div>' 
				,modal: {
					backgroundColor: '#fff' 
                    ,opacity: .5
				}
			}).on('click', function(){ 
				this.hide(); 
			});
			loading.show(); */
		}

		// 隐藏loading对话框
		,hideLoading: function(){
			/*if(!this._loading){
				return;
			}
			this._loading.hide();
			this._loading = null;*/
		}
		
	}

	//页头显示控制
	function controlPageheadview(){
		pageheadHide();
        if(cartApp.isLogin()){
        	$('[act-login-info]').show();
        }else{
        	$('[act-not-login-info]').show();
        }
	}
	//全部隐藏
	function pageheadHide(){
		$('[act-login-info]').hide();
        $('[act-not-login-info]').hide();
	}
	var u=util;
	util_watch.watchOnce($page.name,"renderEnd",u.pipe(cartApp.isCartEmpty,cartApp.loadRecommend));
	util_watch.watch($page.name,"renderEnd",u.ifn(cartApp.isCartEmpty,pageheadHide,controlPageheadview));
	util_watch.watch($page.name,"login",controlPageheadview);
	// 页面加载完毕之后初始化页面，默认显示空购物车页面
	//初始化购物车
	cartApp.init();
	window.cartApp = cartApp;
})();











